
import 'package:flutter/material.dart';

class QuantitySelector extends StatefulWidget {
  final ValueChanged<int>? onChanged;

  const QuantitySelector({
    super.key,
    this.onChanged,
  });

  @override
  State<QuantitySelector> createState() => _QuantitySelectorState();
}

class _QuantitySelectorState extends State<QuantitySelector> {
  final TextEditingController _controller = TextEditingController(text: '1');
  int _value = 1;

  void _updateValue(int newValue) {
    if (newValue < 1 || newValue > 99) return;

    setState(() {
      _value = newValue;
      _controller.text = newValue.toString();
      widget.onChanged?.call(newValue);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 40,
      padding: const EdgeInsets.symmetric(horizontal: 0), // 减小外部容器的padding
      child: Row(
        mainAxisSize: MainAxisSize.min,
        mainAxisAlignment: MainAxisAlignment.center, // 子组件居中对齐
        children: [
          IconButton(        
            padding: EdgeInsets.zero, // 移除按钮内部padding
            icon: Image.asset(
              'assets/images/减.png',
              width: 22,
              height: 22,
            ),
            onPressed: () => _updateValue(_value - 1),
          ),
          Container(
            width: 50, // 控制 TextField 宽度
            height: 28, // 高度设置为28
            alignment: Alignment.center,
            child: TextField(
              controller: _controller,
              textAlign: TextAlign.center, // 确保文字居中
              keyboardType: TextInputType.number,
              maxLength: 2,
              decoration: InputDecoration(
                counterText: '',
                filled: true,
                isDense: true,
                fillColor: const Color(0xFFF7F7F7),
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(8),
                  borderSide: BorderSide.none,
                ),
                contentPadding: EdgeInsets.zero,
              ),
              textAlignVertical: TextAlignVertical.center,
              onChanged: (value) {
                final num = int.tryParse(value) ?? 1;
                _updateValue(num.clamp(1, 99));
              },
            ),
          ),
          IconButton(
            padding: EdgeInsets.zero, // 移除按钮内部padding
            icon: Image.asset(
              'assets/images/加.png',
              width: 23,
              height: 23,
            ),
            onPressed: () => _updateValue(_value + 1),
          ),
        ],
      ),
    );
  }
}
